#!/bin/bash -e

# subq waiting for some seconds

function info() {
echo Usage: `basename $0` '[-n job_name] [-p cpu_num] [-m memery_num] [-q queue_name] [-M email_address] [-P priority_num(-1024 - 1023)] <program and args>'
exit 65
}

echo -e "\n"`basename $0` $@ >>.log || exit 0;



while getopts  ":q:n:p:m:M:Fr:d:t:" opts
do
	case  $opts  in
	p)
		cpu_num=$OPTARG
		;;
	q)
		queue=$OPTARG
		;;
	n)
		name=$OPTARG
		;;
	m)
		mem=$OPTARG
		;;
	M) email=$OPTARG;;
	F) fb=F;;
	r) priority=$OPTARG;;
	d) depend=$OPTARG;;
	t) array=$OPTARG;;
	\?) info;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then info; fi

sleep 21
. $var


if [ -z "$cpu_num" ]; then cpu_num=9; fi
echo cpu num $cpu_num

if [ -z "$mem" ]; then
	mem=21g
elif echo $mem |grep -P '^\d+$' >/dev/null; then
	mem=${mem}g
elif echo $mem |grep -P '^[1-9][0-9]*[mMgG]$'>/dev/null; then
	mem=$mem
else
	echo memery not support $mem; exit 65;
fi
echo mem $mem

if [ -z "$queue" ]; then queue=md; fi
echo queue $queue

if [ -z "$name" ]; then

	if test -z "$fb"; then
		name=_
		facebook=$tools_path/script/facebook.txt
		num1=$(rand_num.sh 1 `cat $facebook |awk 'END{print NR}'` 1)
		name=`sed -n "${num1}p" $facebook`
	else
		name=_
	fi
else
	if test -z "$fb"; then
		facebook=$tools_path/script/facebook.txt
		num1=$(rand_num.sh 1 `cat $facebook |awk 'END{print NR}'` 1)
		face=`sed -n "${num1}p" $facebook`
		name=${name}_$face
	fi
fi

sub_opt="-S/bin/bash -N$name -q$queue -lnodes=1:ppn=$cpu_num,mem=$mem -joe"

if test -n "$email"; then sub_opt="$sub_opt -M$email"; fi
if test -n "$depend"; then sub_opt="$sub_opt -Wdepend=$depend"; fi
if test -n "$array"; then sub_opt="$sub_opt -t$array"; fi

echo $@

exec 1>&6 #return std

# if test -z "$email"; then
	# echo $@ |qsub -S/bin/bash -d. -N$name -q$queue -lnodes=1:ppn=$cpu_num,mem=$mem -joe 
# else
	# echo $@ |qsub -S/bin/bash -d. -N$name -q$queue -lnodes=1:ppn=$cpu_num,mem=$mem -joe -M$email 
# fi


echo -e "cd \$PBS_O_WORKDIR\n$@" |qsub $sub_opt



# echo $1 '...' has been qsubed.
. $cmd_done
